local tArgs = {...}
local packages = config.load("/etc/tpm/package.dat")
local temp = config.load("/etc/tpm/packageInstalled.dat")
local found, value

if not security.getSU() then
 exception.throw("RestrictedOpsException")
 return
end

if #tArgs < 1 then
 gui.printAppInfo("tpm", "package name not specified")
 return
elseif not packages then
 gui.printAppInfo("tpm", "package.dat is missing or corrupt")
 log.writeMessage("package.dat unable to be traversed")
 return
elseif not temp then
 shell.executeScript("/etc/scripts/tpm-recache.tsf")
end

found, value = search.traverseKey(temp, tArgs[1])
if found and value then
 gui.printAppInfo("tpm", "package already installed")
 return
end

gui.printAppInfo("tpm", "traversing package.dat")
local ok, pack = search.traverseValue(packages, tArgs[1])
if ok and pack then
 gui.printAppInfo("tpm", "found corresponding package")
 gui.printAppInfo("tpm", "downloading API files [1/2]")
 local numapi = 1
 local numbin = 1
 local APIInstallFlag = false
 for k,v in pairs(pack.apis) do
  if tpm.downloadAPI(k, v) then
   APIInstallFlag = true
   gui.printAppInfo("tpm", "downloaded API "..k.." ["..tostring(numapi).."]")
  else
   gui.printAppWarning("tpm", "failed to download API "..k)
  end
  numapi = numapi + 1
 end
 gui.printAppInfo("tpm", "downloading binaries [2/2]")
 for k,v in pairs(pack.bins) do
  if tpm.downloadBinary(k, v) then
   gui.printAppInfo("tpm", "downloaded binary "..k.." ["..tostring(numbin).."]")
  else
   gui.printAppWarning("tpm", "failed to download binary "..k)
  end
  numbin = numbin + 1
 end
 table.insert(temp, pack.name)
 log.writeMessage("New package downloaded and installed")
 config.save(temp, "/etc/tpm/packageInstalled.dat")
 gui.printAppSuccess("tpm", "package installed")
 if APIInstallFlag then
  if gui.request("Assemblies were installed, restart") then
   kernel.reboot(false)
  end
 end
else
 gui.printAppInfo("tpm", "unable to find id for "..tArgs[1])
end